#include "MainWindow.h"
#include "ui_MainWindow.h"
#include <QDebug>

#include <QUrl>
#include <QDebug>
#include <QHostAddress>
#include <QNetworkInterface>

static QString getIP() //获取ip地址
{
    QList<QHostAddress> list =QNetworkInterface::allAddresses();
    foreach (QHostAddress address, list)
    {
       if(address.protocol() ==QAbstractSocket::IPv4Protocol)
           return address.toString();
    }
    return "";
}

MainWindow::MainWindow(QWidget *parent) :
    QMainWindow(parent),
    ui(new Ui::MainWindow)
{
    ui->setupUi(this);
    modbusServer = new ModbusServer(this);

    buttonGroup.addButton(ui->OKClear);
    buttonGroup.addButton(ui->NGClear);
    buttonGroup.addButton(ui->SolutionChange);
    buttonGroup.addButton(ui->Connect);

    connect(&buttonGroup, SIGNAL(buttonClicked(QAbstractButton*)), this, SLOT(onButtonClicked(QAbstractButton*)));
    connect(modbusServer, &ModbusServer::newDataReady,  this, &MainWindow::onNewData);
    ui->ipaddress->setText(QString("%1:502").arg(getIP()));

}

MainWindow::~MainWindow()
{
    delete ui;
}


void MainWindow::onNewData(const QString &name, const QVariant &value)
{
    if(name == "OK")
    {
        ui->OKCount->setText(value.toString());
    }else if(name =="NG"){
        ui->NGCount->setText(value.toString());
    }else if(name == "SolutionAdd"){
        ui->Solutions->addItem(value.toString());
        ui->Solutions->setCurrentText(value.toString());
    }else if(name == "message"){
        statusBar()->showMessage(value.toString(), 10000);
    }
}

void MainWindow::onButtonClicked(QAbstractButton *button)
{
    qDebug()<<button->objectName();

    if( button->objectName() =="OKClear")
    {
        modbusServer->setValue("OK", "Clear");
        ui->OKCount->setText("0");
    }
    else if( button->objectName() =="NGClear")
    {
        modbusServer->setValue("NG", "Clear");
        ui->NGCount->setText("0");
    }else if (button->objectName() == "SolutionChange"){
        if(ui->Solutions->count() == 0)
            return;
        modbusServer->setValue("SolutionChange", ui->Solutions->currentText().toInt());
    }else if (button->objectName() == "Connect"){
        if(button->text() == "连接")
        {
            button->setText("断开");
            modbusServer->setValue("Connect", ui->ipaddress->text());
        }else{
            button->setText("连接");
            modbusServer->setValue("Disconnect", 0U);
        }

    }


}
